package com.demo.serviceI.LoginandRegisterI;


import com.demo.exception.ServiceException;
import com.demo.mapper.SysUserModules.SysUserMapper;
import com.demo.model.Register.Register;
import com.demo.model.SysUser.SysUser;
import com.demo.service.LoginandRegister.RegisterService;
import com.demo.tool.Base64Strategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

@Service
public class RegisterServicel implements RegisterService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private Base64Strategy base64Strategy;



    //注册
    @Override
    public int Register(Register register) throws UnsupportedEncodingException {
        SysUser user=new SysUser();
        if(register.getUserName()==null||register.getUserName().length()<=0||register.getPassword()==null||register.getPassword().length()<=0||register.getPhone()==null||register.getPhone().length()<=0||register.getConfirmpassword()==null||register.getConfirmpassword().length()<=0){
             throw new ServiceException("请确认您的用户名,手机号,密码,确认密码不为空及长度不为0");
        }

        //判断是否重名
        if(userMapper.countName(register.getUserName())>0){
            throw new ServiceException("当前用户名重复");
        }
        //判断手机号是否重复
        if(userMapper.countPhone(register.getPhone())>0){
            throw new ServiceException("当前手机号重复");
        }else {
            //不重复就校验手机号是否格式错误
            //判断手机号是否11位
            String phone=register.getPhone();
            if(phone.length()>0&&phone.length()==11){
                //如果通过手机号长度验证，则校验是否合法手机号
                //校验规则
                if(!phone.matches("1[3-9]\\d{9}")){
                    throw new ServiceException("请输入正确的手机号");
                }
            }else {
                throw new ServiceException("手机号长度错误,正确应为11位");
            }
        }

        //判断第一次密码是否和第二次密码一样
        String password=register.getPassword();
        String Confirmpassword=register.getConfirmpassword();
        if(!Confirmpassword.equals(password)){
            throw new ServiceException("确认密码和当前密码不一致");
        }

        //使用base64对密码进行加密
       String encryptionPassword= base64Strategy.encode(Confirmpassword);

         user.setUsername(register.getUserName());
         user.setPhone(register.getPhone());
         user.setPassword(encryptionPassword);
         user.setUid(null);

        return userMapper.save(user);
    }
}
